#include "video.h"

Video::Video()
{
    File root = SD.open("/video");
    if (!root||!root.isDirectory())
    {
        init_gui();
        return;
    }
    File file = root.openNextFile();
    int num_video_tmp=0;
    String file_name;
    while (file&&num_video_tmp<100)
    {
        file_name = file.name();
        if (!file.isDirectory()&&file_name.endsWith(".pokani"))
        {
            video_list[num_video_tmp] = file_name;
            num_video_tmp += 1;
        }
        file = root.openNextFile();
    }
    num_video = num_video_tmp;
    if (num_video>0){
        file_video = SD.open(video_list[no_video]);
    }
    else{
        init_gui();
    }
    
    display_buf = new uint8_t[JPG_BUFFER_SIZE];
    frame_len_buf  = new uint32_t;
}


void Video::init_gui()
{
    scr = lv_obj_create(NULL, NULL);
    lv_obj_set_style_local_bg_color(scr, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK);
	lv_scr_load(scr);

    lv_style_init(&font_style);
	lv_style_set_text_font(&font_style, LV_STATE_DEFAULT, &lv_font_montserrat_34);
	lv_style_set_text_color(&font_style, LV_STATE_DEFAULT, LV_COLOR_WHITE);

    label = lv_label_create(scr, NULL);
	lv_obj_add_style(label, LV_LABEL_PART_MAIN, &font_style);
	lv_label_set_text(label, LV_SYMBOL_EYE_OPEN  " No video!");
	lv_obj_align(label, NULL, LV_ALIGN_CENTER, 0, 0);
    
    lv_task_handler();
}
Event Video::main_process(Action action)
{
    
    tft.startWrite();
    if (action==TURN_RIGHT&&num_video>0)
    {
        file_video.close();
        no_video = (no_video+1)%num_video;
        file_video = SD.open(video_list[no_video]);
    }
    else if(action==TURN_LEFT&&num_video>0)
    {
        file_video.close();
        no_video = (no_video+num_video-1)%num_video;
        file_video = SD.open(video_list[no_video]);
    }
    if (!file_video.available()&&num_video>0)
    {
        file_video.close();
        file_video = SD.open(video_list[no_video]);
    }
    else if (file_video.available())
    {
        for (int i=0;i<10;i++)
        {
            if (file_video.available())
            {
                file_video.read((uint8_t*)frame_len_buf, FRAME_LEN_BUFFER_SIZE);
                frame_len = (size_t)(*frame_len_buf);
                TJpgDec.drawJpg(0, 0, display_buf, file_video.read(display_buf, frame_len));
            }
        }
    }
    return NOEVENT;
}

Video::~Video()
{
    if (scr!=NULL)
        lv_obj_del(scr);
    file_video.close();
    delete display_buf;
    delete frame_len_buf;
}